package com.asia5b.a5mall.goods.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.activity.SearchGoodsActivity
import com.asia5b.a5mall.goods.adapter.GoodsSelectorKeyAdapter
import com.asia5b.a5mall.goods.databinding.FragmentGoodsselectorBinding
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.model.goods.GoodsSelectorModel
import com.asia5b.a5mall.middleware.model.goods.SelectorKeyBean
import kotlinx.android.synthetic.main.fragment_goodsselector.*

/**
 * Created by zhangyuncai on 2020/5/13.
 * todo 与SearchGoodsActivity完全耦合,主要帮忙打理筛选参数
 */
class GoodsSelectorFragment : SimpleFragment<SimpleViewModel, FragmentGoodsselectorBinding>() {
    override val viewModelClazz: Class<SimpleViewModel>
        get() = SimpleViewModel::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentGoodsselectorBinding {
        searchGoodsActivity = mActivity as SearchGoodsActivity
        priceHead = View.inflate(requireContext(), R.layout.item_goodsselector_price_head, null)
        et_goodsselector_price_min = priceHead.findViewById(R.id.et_goodsselector_price_min)
        et_goodsselector_price_max = priceHead.findViewById(R.id.et_goodsselector_price_max)
        return FragmentGoodsselectorBinding.inflate(layoutInflater,container,false)
    }
    lateinit var searchGoodsActivity: SearchGoodsActivity
    lateinit var params: HashMap<String, Any>

    val mAllRecyclerView by lazy { rv_goodsselector }    //所有筛选参数
    val mAllDatas = arrayListOf<SelectorKeyBean>()
    val mAllAdapter by lazy { GoodsSelectorKeyAdapter(mAllDatas, params) }


    lateinit var et_goodsselector_price_min: EditText//最低价
    lateinit var et_goodsselector_price_max: EditText  //最高价
    lateinit var priceHead: View  //价格布局


    override fun initView() {
        //添加价格头部
        mAllAdapter.removeAllHeaderView()
        mAllAdapter.addHeaderView(priceHead)
        mAllRecyclerView.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mAllAdapter
        }
        followParams()
    }

    override fun initEvent() {
        //重置
        tv_goodsselector_reset.setOnClickListener {
            et_goodsselector_price_min.setText("")
            et_goodsselector_price_max.setText("")
            for (mData in mAllDatas) {
                mData.selectItem = null
            }
            mAllAdapter.notifyDataSetChanged()
        }
        //确定
        tv_goodsselector_sure.setOnClickListener {
            submit()
        }

    }

    /**
     * 确定
     */
    fun submit() {

        //价格
        var priceMin = et_goodsselector_price_min.text.toString().trim()
        var priceMax = et_goodsselector_price_max.text.toString().trim()
        if (!TextUtils.isEmpty(priceMin) && !TextUtils.isEmpty(priceMax)) {
            params.put("price", "${priceMin}_${priceMax}")
        } else {
            params.remove("price")
        }

        val stringBuffer = StringBuffer()
        for (selctorKeyBean in mAllDatas) {
            if (selctorKeyBean.isBrand()) {
                if (selctorKeyBean.selectItem != null) {
                    params.put("brand", selctorKeyBean.selectItem?.value?:"")
                }else{
                    params.remove("brand")
                }
            } else if (selctorKeyBean.isCate()) {
                if (selctorKeyBean.selectItem != null) {
                    params.put("category", selctorKeyBean.selectItem?.value?:"")
                }else{
                    params.remove("category")
                }
            } else {
                if (selctorKeyBean.selectItem != null) {
                    stringBuffer.append("${selctorKeyBean.key}_${selctorKeyBean.selectItem?.value?:""}")
                    stringBuffer.append("@")
                }

            }
        }
        if (stringBuffer.length != 0) {
            params.put("prop", stringBuffer.toString().removeSuffix("@"))
        }else{
            params.remove("prop")
        }





        searchGoodsActivity.getDatas(1)
    }

    override fun lazyFetchData() {
    }

    fun searchGoodsSelectorResult(goodsSelectorModel: GoodsSelectorModel) {
        mAllDatas.clear()
        //添加品牌
        if (goodsSelectorModel.brand?.isNullOrEmpty() == false) {
            mAllDatas.add(SelectorKeyBean().apply {
                key = getString(R.string.品牌)
                value = goodsSelectorModel.brand!!
                isShowDividerTop = true
            })
        }
        //添加分类
        if (goodsSelectorModel.cat?.isNullOrEmpty() == false) {
            mAllDatas.add(SelectorKeyBean().apply {
                key = getString(R.string.分类)
                value = goodsSelectorModel.cat!!
                isShowDividerBottom = true
            })
        }
        //添加其他
        if (goodsSelectorModel.prop?.isNullOrEmpty() == false) {
            for (selectorKeyBean in goodsSelectorModel.prop!!) {
                if (selectorKeyBean.value.isNullOrEmpty() == false) {
                    mAllDatas.add(selectorKeyBean)
                }
            }
        }
        mAllAdapter.notifyDataSetChanged()

    }

    /**
     * 跟着参数
     */
    fun followParams() {
        //跟随价格
        if (params.containsKey("price")) {
            try {
                val price = "${params.get("price")}"
                val priceArry=price.split("_")
                et_goodsselector_price_min.setText("${priceArry[0]}")
                et_goodsselector_price_max.setText("${priceArry[1]}")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            et_goodsselector_price_min.setText("")
            et_goodsselector_price_max.setText("")
        }
        for (selectorKeyBean in mAllDatas) {
            //重置
            selectorKeyBean.selectItem = null
            if (selectorKeyBean.isBrand()) {
                if (params.containsKey("brand")) {
                    for (selectorBean in selectorKeyBean.value!!) {
                        if (TextUtils.equals(selectorBean.value, "${params.get("brand")}")) {
                            selectorKeyBean.selectItem = selectorBean
                        }
                    }
                }
            } else if (selectorKeyBean.isCate()) {
                if (params.containsKey("category")) {
                    for (selectorBean in selectorKeyBean.value!!) {
                        if (TextUtils.equals(selectorBean.value, "${params.get("category")}")) {
                            selectorKeyBean.selectItem = selectorBean
                        }
                    }
                }
            } else {
                if (params.containsKey("prop")) {
                    val prop = "${params.get("prop")}"
                    val propStringList = prop.split("@")
                    for (key_value in propStringList) {
                        for (selectorBean in selectorKeyBean.value!!) {
                            if (key_value.contains(selectorBean.value)) {
                                selectorKeyBean.selectItem = selectorBean
                            }
                        }
                    }
                }
            }
        }
        mAllAdapter.notifyDataSetChanged()
    }

}